package com.leyou.order.controller;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.entity.TbOrder;
import com.leyou.order.service.TbOrderService;
import com.leyou.order.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private TbOrderService tbOrderService;
    /**
     * 创建订单
     * @param orderDTO
     * @return
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(@RequestBody OrderDTO orderDTO){
        return ResponseEntity.ok(tbOrderService.createOrder(orderDTO));
    }

    @GetMapping("/{id}")
    public ResponseEntity<OrderVo> findOrderById(@PathVariable(name = "id")Long orderId){
        TbOrder tbOrder = tbOrderService.getById(orderId);
        if(tbOrder == null){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return ResponseEntity.ok(BeanHelper.copyProperties(tbOrder,OrderVo.class));
    }

    /**
     * 获取微信支付返回的codeurl
     * @param orderId
     * @return
     */
    @GetMapping("/url/{id}")
    public ResponseEntity<String> getCodeUrl(@PathVariable(name = "id")Long orderId){
        return ResponseEntity.ok(tbOrderService.getCodeUrl(orderId));
    }

    /**
     * 查询订单的状态
     * @param orderId
     * @return
     */
    @GetMapping("/state/{id}")
    public ResponseEntity<Integer> getOrderStatus(@PathVariable(name = "id")Long orderId){
        TbOrder tbOrder = tbOrderService.getById(orderId);
        if(tbOrder == null){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return ResponseEntity.ok(tbOrder.getStatus());
    }

    /**
     * 查询秒杀订单
     *
     * @param orderId
     * @return
     */
    @GetMapping("/findOrder")
    public ResponseEntity<OrderVo> findOrder(@RequestParam(name = "id",required = false) Long orderId) {
        return ResponseEntity.ok(tbOrderService.findOrderByOrderId(orderId));
    }


}
